package com.creatorblue.config.security;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.creatorblue.bean.UserInfo;
import com.creatorblue.service.UserInfoService;

/**
 * 自定义认证，授权信息
 * @author zhuq
 *
 */
@Configuration
public class CBUserDetailService implements UserDetailsService{

	@Autowired
	private UserInfoService uis;
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//从数据库中根据账号查询用户信息
		UserInfo user = queryByName(username);
		if(user == null) {
			throw new UsernameNotFoundException("用户名不存在");
		}
		//初始化权限标识
		List<GrantedAuthority> auths = new ArrayList<>();
		String perms = user.getPerms();
		if(perms != null && !perms.isEmpty()) {
			for(String perm : perms.split(",")) {
				auths.add(new SimpleGrantedAuthority(perm));
			}
		}
		//将账号，密码，授权标识返回，后续交给security框架完成认证及授权工作
		return new User(username, user.getUserPassword(), auths);
	}

	public UserInfo queryByName(String username) {
		return uis.queryByName(username);
	}
}
